﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using edowork.com.SQL2005;
using edowork.com.Model;

namespace WebInvoicingsys.system.baseset.sysrole
{
    public partial class usermanagement_list : System.Web.UI.Page
    {
        //前台输出提示信息变量
        public string alert_msg = "";

        //传入的参数
        string sysaccount, username, mobile, email, stu1, department, job;

        /// <summary>
        /// 取得传入的参数
        /// </summary>
        /// <returns></returns>
        private bool GetParma()
        {
            try
            {
                sysaccount = Request.Params["sysaccount"].ToString();
                username = Request.Params["username"].ToString();
                mobile = Request.Params["mobile"].ToString();
                email = Request.Params["email"].ToString();
                stu1 = Request.Params["stu1"].ToString();
                department = Request.Params["department"].ToString();
                job = Request.Params["job"].ToString();
            }
            catch
            {
                //显示出错信息
                alert_msg = String.Format(Scripts.alert_warning, Errormsg.er_Parampost);
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);
                return false;
            }

            return true;
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        /// <returns></returns>
        private DataSet GetData()
        {
            //取得传入的参数
            if (GetParma() == false)
            {
                return null;
            }

            string error_msg = "";

            //构造SQL语句
            string sql = @"select a.userid, a.sysaccount, a.username, a.mobile, a.email, a.stu1, a.remark, a.sysdate, b.jobremark, c.departmentremark, e.rulegroupremark
                            from sysuser a, job b, department c, sysuserrule d, rulegroup e
                              where a.departmentid=c.departmentid 
                                and a.jobid=b.jobid
                                and a.userid = d.userid 
                                and d.rulegroupid=e.rulegroupid";

            sql += (sysaccount == "") ? "" : String.Format(" and sysaccount like '%{0}%'", sysaccount);
            sql += (username == "") ? "" : String.Format(" and username like '%{0}%'", username);
            sql += (mobile == "") ? "" : String.Format(" and mobile like '%{0}%'", mobile);
            sql += (email == "") ? "" : String.Format(" and email like '%{0}%'", email);
            sql += (stu1 == "") ? "" : String.Format(" and stu1 = '{0}'", stu1);
            sql += (department == "") ? "" : String.Format(" and departmentid = '{0}'", department);
            sql += (job == "") ? "" : String.Format(" and jobid = '{0}'", job);

            Execute exec = new Execute(Session["connectionString"].ToString());

            DataSet ds = exec.ExecSQLQueryDataSet(sql, ref error_msg);

            if (ds == null)
            {
                //显示出错信息
                alert_msg = String.Format(Scripts.alert_warning, error_msg);
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);
                return null;
            }

            DataSet dsResult = new DataSet();

            //绑定菜单
            DataTable dt = new DataTable("List");

            dt.Columns.Add("dgvID");
            dt.Columns.Add("userid");
            dt.Columns.Add("departmentid");
            dt.Columns.Add("jobid");
            dt.Columns.Add("sysaccount");
            dt.Columns.Add("username");
            dt.Columns.Add("mobile");
            dt.Columns.Add("email");
            dt.Columns.Add("stu1");
            dt.Columns.Add("rulegroupremark");
            dt.Columns.Add("remark");
            dt.Columns.Add("sysdate");

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                DataRow drnew = dt.NewRow();

                drnew["dgvID"] = (dt.Rows.Count + 1).ToString();
                drnew["userid"] = dr["userid"].ToString();
                drnew["departmentid"] = dr["departmentremark"].ToString();
                drnew["jobid"] = dr["jobremark"].ToString();
                drnew["sysaccount"] = dr["sysaccount"].ToString();
                drnew["username"] = dr["username"].ToString();
                drnew["mobile"] = dr["mobile"].ToString();
                drnew["email"] = dr["email"].ToString();
                drnew["stu1"] = (dr["stu1"].ToString() == "0" ? "禁用" : "启用");
                drnew["rulegroupremark"] = dr["rulegroupremark"].ToString();
                drnew["remark"] = dr["remark"].ToString();
                drnew["sysdate"] = dr["sysdate"].ToString();

                dt.Rows.Add(drnew);
            }

            dsResult.Tables.Add(dt);

            return dsResult;
        }

        /// <summary>
        /// 绑定数据
        /// </summary>
        private void bind()
        {
            DataSet ds = GetData();

            if (ds == null)
            {
                return;
            }

            rplist.DataSource = ds.Tables[0];
            rplist.DataBind();
        }

        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="id"></param>
        private void delete(string id)
        {
            if (String.IsNullOrEmpty(id))
            {
                return;
            }

            alert_msg = "";

            using (edowork.com.SQL2005.TranUtil tranutil = new TranUtil(Session["connectionString"].ToString()))
            {
                System.Data.SqlClient.SqlTransaction tran = null;

                try
                {
                    tran = tranutil.GetSqlTransaction();
                }
                catch (Exception er)
                {
                    alert_msg = String.Format(Scripts.alert_warning, er.Message);

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                edowork.com.SQL2005.Execute exec = new Execute(Session["connectionString"].ToString());

                string sql = "";
                int result = -1;

                //删除sysuserrule中数据
                sql = String.Format("delete from sysuserrule where userid='{0}'", id);

                result = exec.ExecSQLQueryInt(sql, ref alert_msg, tran);

                if (result <= 0)
                {
                    tran.Rollback();
                    tranutil.CloseConnection();

                    alert_msg = String.Format(Scripts.alert_warning, alert_msg);

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                //删除sysuser中数据
                sql = String.Format("delete from sysuser where userid='{0}'", id);

                result = exec.ExecSQLQueryInt(sql, ref alert_msg, tran);

                if (result <= 0)
                {
                    tran.Rollback();
                    tranutil.CloseConnection();

                    alert_msg = String.Format(Scripts.alert_warning, alert_msg);

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                tran.Commit();
                tranutil.CloseConnection();
            }

            alert_msg = String.Format(Scripts.alert_success, Errormsg.success_Delete);

            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="id"></param>
        private void edit(string id)
        {
            if (String.IsNullOrEmpty(id))
            {
                return;
            }

            if (GetParma() == false)
            {
                return;
            }

            string url = "/system/baseset/sysrole/usermanagement_edit.aspx?id={0}&sysaccount={1}&username={2}&mobile={3}&email={4}&stu1={5}&department={6}&job={7}";

            url = String.Format(url, id, sysaccount, username, mobile, email, stu1, department, job);

            Response.Redirect(url);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //查询
                bind();
            }
        }

        //返回
        protected void btnReturn_Click(object sender, EventArgs e)
        {
            string url = "/system/baseset/sysrole/usermanagement.aspx";

            Response.Redirect(url);
        }

        //导出
        protected void btnExport_Click(object sender, EventArgs e)
        {
            //取得数据
            DataSet ds = GetData();

            if (ds == null)
            {
                return;
            }

            //构造导出表头
            String[] headname = { "序号", "用户编码", "所在部门", "所任职务", "登陆账号", "用户名称", "移动电话", "电子邮箱", "启用状态", "所属分组", "备注", "创建时间" };

            //导出
            ExportToFile.ExportToExcel(ds.Tables[0], HttpContext.Current.Response, headname);
        }

        //删除与编辑
        protected void rplist_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            string id = e.CommandArgument.ToString();

            switch (e.CommandName)
            {
                case "Delete":
                    {
                        delete(id);

                        bind();

                        break;
                    }
                case "Edit":
                    {
                        edit(id);

                        bind();

                        break;
                    }
                default:
                    {
                        break;
                    }
            }
        }
    }
}